<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12" md="6">
        <h1 class="text-h4 font-weight-bold">
          {{ pageTitle }}
        </h1>
      </v-col>
      <v-col cols="12" md="6" class="d-flex justify-end align-center">
        <v-btn color="primary" prepend-icon="mdi-file-excel" @click="openImportDialog()">
          导入学生
        </v-btn>
        <v-btn color="primary" prepend-icon="mdi-plus" @click="openStudentDialog()">
          添加学生
        </v-btn>
      </v-col>
    </v-row>

    <!-- 筛选和搜索 -->
    <v-row class="mb-6">
      <v-col cols="12" md="3">
        <v-select v-model="selectedClass" :items="classOptions" label="筛选班级" variant="filled" density="comfortable"
          clearable @update:model-value="loadStudents"></v-select>
      </v-col>
      <v-col cols="12" md="9">
        <v-text-field v-model="searchText" prepend-inner-icon="mdi-magnify" label="搜索学生姓名或学号" variant="filled"
          density="comfortable" clearable></v-text-field>
      </v-col>
    </v-row>

    <!-- 学生列表 -->
    <v-card>
      <v-card-text>
        <!-- 移动端完整视图 -->
        <div v-if="mobile" class="mobile-student-list">
          <v-card v-for="student in paginatedMobileStudents" :key="student.id" class="mb-3" variant="outlined">
            <v-card-text class="pa-2">
              <!-- 头部信息：头像、姓名、学号、班级 -->
              <div class="d-flex align-center mb-2">
                <v-avatar :color="getAvatarColor(student.name)" size="32" class="me-2">
                  <span class="text-white text-caption">{{ student.name.charAt(0) }}</span>
                </v-avatar>
                <div class="flex-grow-1">
                  <div class="d-flex align-center justify-space-between">
                    <div>
                      <div class="font-weight-medium text-body-2">{{ student.name }}</div>
                      <div class="text-caption text-medium-emphasis">{{ student.student_no }}</div>
                    </div>
                    <div class="d-flex flex-column gap-1">
                      <v-chip color="primary" size="x-small" variant="elevated">
                        {{ student.class_name }}
                      </v-chip>
                      <v-chip v-if="student.assigned_bus_id" color="success" size="x-small" variant="elevated">
                      司机: {{ getStudentDriverName(student) }}
                    </v-chip>
                      <v-chip v-else color="grey" size="x-small" variant="outlined">
                        未分配司机
                      </v-chip>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 考勤状态：紧凑排列 -->
              <div class="mb-2">
                <div class="d-flex align-center justify-space-between">
                  <!-- 入园状态 -->
                  <div class="d-flex align-center gap-1">
                    <span class="text-caption text-medium-emphasis">入园:</span>
                    <v-chip v-if="student.arrival_status" :color="getAttendanceColor(student.arrival_status)"
                      size="x-small" variant="elevated">
                      {{ getAttendanceText('arrival', student.arrival_status) }}
                    </v-chip>
                    <v-chip v-else color="grey" size="x-small" variant="outlined">
                      未入园
                    </v-chip>
                  </div>

                  <!-- 离园状态 -->
                  <div class="d-flex align-center gap-1">
                    <span class="text-caption text-medium-emphasis">离园:</span>
                    <v-chip v-if="student.departure_status" :color="getDepartureColor(student.departure_status)"
                      size="x-small" variant="elevated">
                      {{ getAttendanceText('departure', student.departure_status) }}
                    </v-chip>
                    <v-chip v-else-if="student.arrival_status === 'present'" color="blue" size="x-small" variant="outlined">
                      在园中
                    </v-chip>
                    <v-chip v-else-if="student.arrival_status === 'leave'" color="orange" size="x-small" variant="outlined">
                      请假
                    </v-chip>
                    <v-chip v-else color="grey" size="x-small" variant="outlined">
                      未入园
                    </v-chip>
                  </div>
                </div>
                <!-- 时间信息（如果有的话） -->
                <div v-if="student.arrival_time || student.departure_time" class="d-flex justify-space-between mt-1">
                  <span v-if="student.arrival_time" class="text-caption text-medium-emphasis">
                    入园: {{ student.arrival_time }}
                  </span>
                  <span v-if="student.departure_time" class="text-caption text-medium-emphasis">
                    离园: {{ student.departure_time }}
                  </span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="d-flex justify-end gap-1">
                <v-btn size="small" variant="outlined" color="primary" icon="mdi-pencil"
                  @click="openStudentDialog(student)"></v-btn>
                <v-btn size="small" variant="outlined" color="orange" icon="mdi-bus"
                  @click="openDriverAssignDialog(student)" :title="student.assigned_bus_id ? '更改司机' : '分配司机'"></v-btn>
                <v-btn size="small" variant="outlined" color="success" icon="mdi-account-check"
                  @click="openStatusDialog(student)"></v-btn>
                <v-btn size="small" variant="outlined" color="error" icon="mdi-delete"
                  @click="deleteStudent(student)"></v-btn>
              </div>
            </v-card-text>
          </v-card>

          <!-- 移动端分页 -->
          <div class="d-flex justify-center mt-4">
            <v-pagination v-model="mobilePage" :length="mobilePageCount" :total-visible="5" size="small"></v-pagination>
          </div>
        </div>

        <!-- 桌面端数据表格 -->
        <v-data-table v-else :headers="headers" :items="studentsStore.students" :loading="studentsStore.loading" class="elevation-1"
          :items-per-page="15">
          <template v-slot:item.name="{ item }">
            <div class="d-flex align-center">
              <v-avatar :color="getAvatarColor(item.name)" size="32" class="me-3">
                <span class="text-white text-caption">{{ item.name.charAt(0) }}</span>
              </v-avatar>
              <div>
                <div class="font-weight-medium">{{ item.name }}</div>
                <div class="text-caption text-medium-emphasis">{{ item.student_no }}</div>
              </div>
            </div>
          </template>

          <template v-slot:item.class_name="{ item }">
            <v-chip color="primary" size="small" variant="elevated">
              {{ item.class_name }}
            </v-chip>
          </template>

          <template v-slot:item.assigned_driver="{ item }">
            <div v-if="item.assigned_bus_id">
              <v-chip color="success" size="small" variant="elevated">
                {{ getStudentDriverName(item) }}
              </v-chip>
            </div>
            <div v-else>
              <v-chip color="grey" size="small" variant="outlined">
                未分配
              </v-chip>
            </div>
          </template>

          <template v-slot:item.attendance_status="{ item }">
            <div class="d-flex flex-column gap-1">
              <!-- 入园状态 -->
              <v-chip v-if="item.arrival_status" :color="getAttendanceColor(item.arrival_status)" size="x-small"
                variant="elevated">
                {{ getAttendanceText('arrival', item.arrival_status) }}
                <span v-if="item.arrival_time" class="ml-1">{{ item.arrival_time }}</span>
              </v-chip>
              <v-chip v-else color="grey" size="x-small" variant="outlined">
                未入园
              </v-chip>

              <!-- 离园状态 -->
              <v-chip v-if="item.departure_status" :color="getDepartureColor(item.departure_status)" size="x-small"
                variant="elevated">
                {{ getAttendanceText('departure', item.departure_status) }}
                <span v-if="item.departure_time" class="ml-1">{{ item.departure_time }}</span>
              </v-chip>
              <v-chip v-else-if="item.arrival_status" color="blue" size="x-small" variant="outlined">
                在园中
              </v-chip>
            </div>
          </template>





          <template v-slot:item.actions="{ item }">
            <v-btn icon size="small" variant="text" @click="openStudentDialog(item)">
              <v-icon>mdi-pencil</v-icon>
            </v-btn>

            <v-btn icon size="small" variant="text" color="primary" @click="openDriverAssignDialog(item)" 
                   :title="item.assigned_bus_id ? '更改司机' : '分配司机'">
              <v-icon>mdi-bus</v-icon>
            </v-btn>

            <v-btn icon size="small" variant="text" color="success" @click="openStatusDialog(item)">
              <v-icon>mdi-account-check</v-icon>
            </v-btn>

            <v-btn icon size="small" variant="text" color="error" @click="deleteStudent(item)">
              <v-icon>mdi-delete</v-icon>
            </v-btn>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- 学生编辑对话框 -->
    <v-dialog v-model="studentDialog" max-width="600">
      <v-card>
        <v-card-title>
          {{ editingStudent?.id ? '编辑学生' : '添加学生' }}
        </v-card-title>

        <v-card-text>
          <v-form ref="studentFormRef" @submit.prevent="saveStudent">
            <v-row>
              <v-col cols="12" sm="6">
                <v-text-field v-model="studentForm.student_no" label="学号" variant="filled" density="comfortable"
                  :rules="studentNoRules" required></v-text-field>
              </v-col>
              <v-col cols="12" sm="6">
                <v-text-field v-model="studentForm.name" label="姓名" variant="filled" density="comfortable"
                  :rules="nameRules" required></v-text-field>
              </v-col>
              <v-col cols="12">
                <v-select v-model="studentForm.class_id" :items="classOptions" label="班级" variant="filled"
                  density="comfortable" :rules="classRules" required></v-select>
              </v-col>
              <v-col cols="12">
                <v-select v-model="studentForm.assigned_bus_id" :items="driverOptions" label="分配校车司机" variant="filled"
                  density="comfortable" clearable hint="为学生分配固定的校车司机，可选项"></v-select>
              </v-col>

            </v-row>
          </v-form>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="closeStudentDialog">取消</v-btn>
          <v-btn color="primary" @click="saveStudent" :loading="saving">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>


    
    <!-- 司机分配对话框 -->
    <v-dialog v-model="driverAssignDialog" max-width="500">
      <v-card>
        <v-card-title class="text-h6">
          <v-icon class="mr-2">mdi-bus</v-icon>
          {{ selectedStudentForDriver?.assigned_bus_id ? '更改司机' : '分配司机' }}
        </v-card-title>
        
        <v-card-text>
          <div class="mb-4">
            <p><strong>学生：</strong>{{ selectedStudentForDriver?.name }}</p>
            <p><strong>学号：</strong>{{ selectedStudentForDriver?.student_no }}</p>
            <p><strong>班级：</strong>{{ selectedStudentForDriver?.class_name }}</p>
            <p v-if="selectedStudentForDriver?.assigned_bus_id"><strong>当前司机：</strong>{{ getStudentDriverName(selectedStudentForDriver) }}</p>
          </div>
          
          <v-select 
            v-model="assignDriverForm.assigned_bus_id" 
            :items="driverOptions" 
            label="选择司机" 
            variant="filled" 
            density="comfortable" 
            clearable
            hint="选择要分配的校车司机，留空表示不分配司机"
            persistent-hint
          ></v-select>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="closeDriverAssignDialog">取消</v-btn>
          <v-btn color="primary" @click="saveDriverAssignment" :loading="assigningDriver">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Excel导入对话框 -->
    <v-dialog v-model="importDialog" max-width="500">
      <v-card>
        <v-card-title class="text-h6">
          <v-icon class="mr-2">mdi-file-excel</v-icon>
          导入学生数据
        </v-card-title>
        <v-card-text>
          <p class="mb-4">请选择Excel文件(.xlsx)导入学生数据。文件应包含以下列：</p>
          <ul class="mb-4">
            <li>学号 (student_no) - <strong>必填</strong></li>
            <li>姓名 (name) - <strong>必填</strong></li>
            <li>班级ID (class_id) - <strong>必填</strong>，如不提供，将使用下方选择的默认班级</li>
            <li>司机ID (driver_id) - <strong>可选</strong>，分配给学生的校车司机ID</li>
          </ul>
          <div class="mb-4 pa-3 bg-blue-lighten-5 rounded">
            <v-icon class="mr-2" color="blue">mdi-information</v-icon>
            <strong>导入模板说明：</strong>
            <br>• Excel第一行为列标题：学号、姓名、班级ID、司机ID
            <br>• 学号和姓名为必填项
            <br>• 班级ID可以在下方选择默认值，或在Excel中为每个学生指定
            <br>• 司机ID为可选项，用于分配校车司机
            <div class="mt-3">
              <v-btn 
                color="primary" 
                variant="outlined" 
                size="small"
                prepend-icon="mdi-download"
                @click="downloadTemplate"
              >
                下载导入模板
              </v-btn>
            </div>
          </div>
          <v-file-input
            v-model="importFile"
            label="选择Excel文件"
            accept=".xlsx"
            prepend-icon="mdi-file-excel"
            show-size
            variant="outlined"
            density="comfortable"
            :rules="[v => !!v || '请选择文件']"
          ></v-file-input>
          <v-select
            v-model="selectedImportClass"
            :items="classOptions"
            label="默认班级（可选）"
            variant="outlined"
            density="comfortable"
            hint="如果Excel中未指定班级ID，将使用此班级"
            persistent-hint
            clearable
          ></v-select>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="primary"
            :loading="importing"
            :disabled="!importFile"
            @click="importStudents"
          >
            导入
          </v-btn>
          <v-btn color="grey" @click="importDialog = false">
            取消
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 学生状态管理对话框 -->
    <v-dialog v-model="statusDialog" max-width="500">
      <v-card>
        <v-card-title>
          修改学生状态 - {{ selectedStudent?.name }}
        </v-card-title>

        <v-card-text>
          <v-form ref="statusFormRef">
            <v-row>
              <v-col cols="12">
                <v-select v-model="statusForm.arrival_status" :items="arrivalStatusOptions" label="入园状态"
                  variant="filled" density="comfortable" clearable></v-select>
              </v-col>
              <v-col cols="12">
                <v-select v-model="statusForm.departure_status" :items="departureStatusOptions" label="离园方式"
                  variant="filled" density="comfortable" clearable></v-select>
              </v-col>
              <!-- 校车选择（仅在选择校车离园时显示） -->
              <v-col cols="12" v-if="statusForm.departure_status === 'bus'">
                <v-select v-model="statusForm.bus_no" :items="busOptions" label="选择校车" variant="filled"
                  density="comfortable" :rules="[v => statusForm.departure_status !== 'bus' || !!v || '请选择校车']"
                  required></v-select>
              </v-col>
              <v-col cols="12">
                <v-textarea v-model="statusForm.notes" label="备注" variant="filled" density="comfortable" rows="3"
                  placeholder="请输入状态变更的备注信息..."></v-textarea>
              </v-col>
            </v-row>
          </v-form>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="closeStatusDialog">取消</v-btn>
          <v-btn color="primary" @click="saveStudentStatus" :loading="statusSaving">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { useDisplay } from 'vuetify'
import { useStudentsStore } from '@/stores/students'
import { useSocketStore } from '@/stores/socket'
import { useAuthStore } from '@/stores/auth'
import * as XLSX from 'xlsx'

const route = useRoute()
const { mobile } = useDisplay()
const studentsStore = useStudentsStore()
const socketStore = useSocketStore()
const authStore = useAuthStore()

// 响应式数据
const saving = ref(false)
const searchText = ref('')
const selectedClass = ref('')// 对话框状态
const studentDialog = ref(false)
const statusDialog = ref(false) // 状态管理对话框
const importDialog = ref(false) // 导入对话框
const driverAssignDialog = ref(false) // 司机分配对话框

// 导入相关
const importFile = ref(null)
const selectedImportClass = ref(null)
const importing = ref(false)
const statusSaving = ref(false) // 状态保存加载状态
const assigningDriver = ref(false) // 司机分配加载状态
const editingStudent = ref(null)
const selectedStudent = ref(null) // 添加选中的学生变量
const selectedStudentForDriver = ref(null) // 司机分配选中的学生
const mobilePage = ref(1)
const mobileItemsPerPage = ref(10)

const studentForm = reactive({ 
  student_no: '',
  name: '',
  class_id: '',
  assigned_bus_id: '' // 分配的校车司机ID
})

// 状态管理表单
const statusForm = reactive({
  arrival_status: '',
  departure_status: '',
  bus_no: '', // 校车编号
  notes: ''
})

// 司机分配表单
const assignDriverForm = reactive({
  assigned_bus_id: ''
})

const studentFormRef = ref(null)
const statusFormRef = ref(null)

// 表格标题
const headers = [
  { title: '学生信息', key: 'name', sortable: true },
  { title: '班级', key: 'class_name', sortable: true },
  { title: '校车司机', key: 'assigned_driver', sortable: false },
  { title: '考勤状态', key: 'attendance_status', sortable: false },
  { title: '操作', key: 'actions', sortable: false }
]


const pageTitle = computed(() => {
  const className = route.query.className
  return className ? `${decodeURIComponent(className)} - 学生管理` : '学生管理'
})

const pageSubtitle = computed(() => {
  const className = route.query.className
  return className ? `管理 ${decodeURIComponent(className)} 的学生信息` : '管理全校学生信息和班级分配'
})

const classOptions = computed(() => {
  return (studentsStore.classesList || []).map(cls => ({
    title: `${cls.name} (${cls.grade})`,
    value: cls.id
  }))
})

const mobilePageCount = computed(() => {
  return Math.ceil(studentsStore.students.length / mobileItemsPerPage.value)
})

const paginatedMobileStudents = computed(() => {
  const start = (mobilePage.value - 1) * mobileItemsPerPage.value
  const end = start + mobileItemsPerPage.value
  return studentsStore.students.slice(start, end)
})

// 状态选项
const arrivalStatusOptions = [
  { title: '已到', value: 'present' },
  { title: '请假', value: 'leave' },
  { title: '异常', value: 'abnormal' }
]

const departureStatusOptions = [
  { title: '校车', value: 'bus' },
  { title: '家长接领', value: 'parent_pickup' },
  { title: '晚托班', value: 'after_school' },
  { title: '特色课程', value: 'special_course' }
]

// 校车选项（用于状态管理对话框）
const busOptions = computed(() => {
  return studentsStore.drivers.map(driver => ({
    title: `${driver.bus_no} - ${driver.name}`,
    value: driver.bus_no
  }))
})

// 司机选项（用于学生分配校车）
const driverOptions = computed(() => {
  return studentsStore.drivers.map(driver => ({
    title: `${driver.name} (${driver.bus_no})`,
    value: driver.id
  }))
})

// 移除了不必要的过滤逻辑，直接显示从后端获取的数据

// 验证规则
const studentNoRules = [
  v => !!v || '学号不能为空',
  v => /^\d+$/.test(v) || '学号只能包含数字'
]

const nameRules = [
  v => !!v || '姓名不能为空',
  v => v.length >= 2 || '姓名至少2个字符'
]

const classRules = [
  v => !!v || '请选择班级'
]



// 方法
const loadStudents = async () => {
  try {
    const params = selectedClass.value ? { classId: selectedClass.value } : {}
    console.log('Frontend Debug - Loading students with params:', params)
    console.log('Frontend Debug - selectedClass.value:', selectedClass.value)
    await studentsStore.fetchStudentsForAdmin(params)
  } catch (error) {
    console.error('加载学生列表失败:', error)
    window.showNotification?.('加载学生列表失败', 'error')
  }
}

const loadClasses = async () => {
  try {
    await studentsStore.fetchClasses()
    return studentsStore.classesList
  } catch (error) {
    console.error('加载班级列表失败:', error)
    return []
  }
}

// 加载司机列表
const loadDrivers = async () => {
  try {
    await studentsStore.fetchDrivers()
  } catch (error) {
    console.error('加载司机列表失败:', error)
    window.showNotification?.('加载司机列表失败', 'error')
  }
}

const resetStudentForm = () => {
  Object.assign(studentForm, {
    student_no: '',
    name: '',
    class_id: selectedClass.value || '',
    assigned_bus_id: '' // 重置校车分配
  })
  // 重置表单验证状态
  if (studentFormRef.value) {
    studentFormRef.value.resetValidation()
  }
}

const closeStudentDialog = () => {
  studentDialog.value = false
  // 延迟重置表单，确保对话框完全关闭后再重置
  setTimeout(() => {
    resetStudentForm()
    editingStudent.value = null
  }, 200)
}

const openStudentDialog = (student = null) => {
  editingStudent.value = student
  if (student) {
    Object.assign(studentForm, {
      student_no: student.student_no,
      name: student.name,
      class_id: student.class_id,
      assigned_bus_id: student.assigned_bus_id || '' // 加载现有的校车分配
    })
  } else {
    resetStudentForm()
  }
  studentDialog.value = true
}

const saveStudent = async () => {
  const { valid } = await studentFormRef.value.validate()
  if (!valid) return

  saving.value = true
  try {
    if (editingStudent.value?.id) {
      // 更新学生
      await studentsStore.updateStudent(editingStudent.value.id, studentForm)
      window.showNotification?.('学生信息更新成功', 'success')
    } else {
      // 创建学生
      await studentsStore.createStudent(studentForm)
      window.showNotification?.('学生添加成功', 'success')
    }

    studentDialog.value = false
    loadStudents()

  } catch (error) {
    console.error('保存学生失败:', error)
    window.showNotification?.('保存学生失败', 'error')
  } finally {
    saving.value = false
  }
}

const deleteStudent = async (student) => {
  if (!confirm(`确定要删除学生 "${student.name}" 吗？`)) return

  try {
    await studentsStore.deleteStudent(student.id)
    loadStudents()
    window.showNotification?.('学生删除成功', 'success')
  } catch (error) {
    console.error('删除学生失败:', error)
    window.showNotification?.('删除学生失败', 'error')
  }
}



// 状态管理相关方法
const openStatusDialog = async (student) => {
  selectedStudent.value = student

  // 获取学生当前详细状态
  try {
    const response = await studentsStore.fetchStudentDetail(student.id)
    const studentDetail = response.data

    // 预填充当前状态
    statusForm.arrival_status = studentDetail.arrival_status || ''
    statusForm.departure_status = studentDetail.departure_status || ''

    // 如果是校车离园，从备注中提取校车编号
    if (studentDetail.departure_status === 'bus' && studentDetail.departure_notes) {
      const busMatch = studentDetail.departure_notes.match(/校车:\s*([^)]+)/)
      statusForm.bus_no = busMatch ? busMatch[1] : ''
    } else {
      statusForm.bus_no = ''
    }

    statusForm.notes = ''
  } catch (error) {
    console.error('获取学生详细信息失败:', error)
    // 使用列表中的基本信息作为备选
    statusForm.arrival_status = student.arrival_status || ''
    statusForm.departure_status = student.departure_status || ''

    // 如果是校车离园，尝试从备注中提取校车编号
    if (student.departure_status === 'bus' && student.notes) {
      const busMatch = student.notes.match(/校车:\s*([^)]+)/)
      statusForm.bus_no = busMatch ? busMatch[1] : ''
    } else {
      statusForm.bus_no = ''
    }

    statusForm.notes = ''
  }

  statusDialog.value = true
}

const closeStatusDialog = () => {
  statusDialog.value = false
  selectedStudent.value = null
  // 重置表单
  statusForm.arrival_status = ''
  statusForm.departure_status = ''
  statusForm.bus_no = ''
  statusForm.notes = ''
}

const saveStudentStatus = async () => {
  if (!selectedStudent.value) return

  // 验证表单
  const { valid } = await statusFormRef.value.validate()
  if (!valid) return

  statusSaving.value = true
  try {
    let finalNotes = statusForm.notes || ''

    // 如果选择了校车离园，将校车信息添加到备注中
    if (statusForm.departure_status === 'bus' && statusForm.bus_no) {
      finalNotes = finalNotes ? `${finalNotes} (校车: ${statusForm.bus_no})` : `校车: ${statusForm.bus_no}`
    }

    const payload = {
      student_id: parseInt(selectedStudent.value.id), // 确保是整数
      arrival_status: statusForm.arrival_status || null,
      departure_status: statusForm.departure_status || null,
      bus_no: statusForm.departure_status === 'bus' ? statusForm.bus_no : null,
      notes: finalNotes || null
    }

    await studentsStore.updateStudentStatus(selectedStudent.value.id, payload)
    window.showNotification?.('学生状态更新成功', 'success')
    closeStatusDialog()
    // 重新加载学生列表以显示最新状态
    await loadStudents()
  } catch (error) {
    console.error('更新学生状态失败:', error)
    window.showNotification?.('更新学生状态失败', 'error')
  } finally {
    statusSaving.value = false
  }
}

const getAvatarColor = (name) => {
  const colors = ['primary', 'secondary', 'accent', 'info', 'success', 'warning']
  const index = name.charCodeAt(0) % colors.length
  return colors[index]
}

// 获取考勤状态颜色
const getAttendanceColor = (status) => {
  const colorMap = {
    'present': 'green',
    'leave': 'orange',
    'abnormal': 'red',
    'absent': 'grey'
  }
  return colorMap[status] || 'grey'
}

// 获取离园状态颜色
const getDepartureColor = (status) => {
  const colorMap = {
    'bus': 'blue',
    'parent_pickup': 'purple',
    'after_school': 'teal',
    'special_course': 'indigo',
    'abnormal': 'red'
  }
  return colorMap[status] || 'grey'
}

// 获取考勤状态文本
const getAttendanceText = (type, status) => {
  if (type === 'arrival') {
    const textMap = {
      'present': '已到校',
      'leave': '请假',
      'abnormal': '异常',
      'absent': '未到'
    }
    return textMap[status] || '未知'
  } else if (type === 'departure') {
    const textMap = {
      'bus': '校车',
      'parent_pickup': '家长接',
      'after_school': '晚托班',
      'special_course': '特色课程',
      'abnormal': '异常离园'
    }
    return textMap[status] || '未知'
  }
  return '未知'
}

// 根据司机ID获取司机姓名
const getDriverName = (driverId) => {
  const driver = studentsStore.drivers.find(d => d.id === driverId)
  return driver ? driver.name : '未知司机'
}

// 根据学生数据获取司机姓名（优先使用学生数据中的司机信息）
const getStudentDriverName = (student) => {
  if (student.driver_name) {
    return student.driver_name
  }
  return getDriverName(student.assigned_bus_id)
}

// 司机分配相关方法
const openDriverAssignDialog = (student) => {
  selectedStudentForDriver.value = student
  assignDriverForm.assigned_bus_id = student.assigned_bus_id || ''
  driverAssignDialog.value = true
}

const closeDriverAssignDialog = () => {
  driverAssignDialog.value = false
  selectedStudentForDriver.value = null
  assignDriverForm.assigned_bus_id = ''
}

const saveDriverAssignment = async () => {
  if (!selectedStudentForDriver.value) return

  assigningDriver.value = true
  try {
    await studentsStore.updateStudent(selectedStudentForDriver.value.id, {
      assigned_bus_id: assignDriverForm.assigned_bus_id || null
    })
    
    window.showNotification?.('司机分配更新成功', 'success')
    closeDriverAssignDialog()
    await loadStudents()
  } catch (error) {
    console.error('更新司机分配失败:', error)
    window.showNotification?.('更新司机分配失败', 'error')
  } finally {
    assigningDriver.value = false
  }
}

// 导入学生相关方法
const openImportDialog = () => {
  importFile.value = null
  selectedImportClass.value = selectedClass.value || null
  importDialog.value = true
}

// 下载导入模板
const downloadTemplate = () => {
  // 创建模板数据
  const templateData = [
    ['学号', '姓名', '班级ID', '司机ID'],
    ['2024001', '张三', '1', ''],
    ['2024002', '李四', '1', '2'],
    ['2024003', '王五', '2', ''],
    ['2024004', '赵六', '2', '3'],
    ['2024005', '钱七', '1', '2']
  ]
  
  // 使用XLSX库创建工作簿
  const XLSX = window.XLSX
  if (!XLSX) {
    window.showNotification?.('XLSX库未加载，请刷新页面重试', 'error')
    return
  }
  
  const ws = XLSX.utils.aoa_to_sheet(templateData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '学生导入模板')
  
  // 下载XLSX文件
  XLSX.writeFile(wb, '学生导入模板.xlsx')
  
  window.showNotification?.('模板下载成功', 'success')
}

const importStudents = async () => {
  if (!importFile.value) return
  
  importing.value = true
  try {
    // 读取Excel文件
    const reader = new FileReader()
    reader.onload = async (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        
        // 获取第一个工作表
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
        const jsonData = XLSX.utils.sheet_to_json(firstSheet)
        
        if (jsonData.length === 0) {
          window.showNotification?.('Excel文件中没有数据', 'error')
          importing.value = false
          return
        }
        
        // 处理数据，确保字段名称匹配
        const processedData = jsonData.map(row => ({
          student_no: row['学号'] || row['student_no'] || '',
          name: row['姓名'] || row['name'] || '',
          class_id: row['班级ID'] || row['class_id'] || selectedImportClass.value,
          driver_id: row['司机ID'] || row['driver_id'] || null
        }))
        
        // 使用WebSocket发送到后端
        socketStore.socket.emit('import-students', {
          students: processedData,
          userId: authStore.userId,
          userRole: authStore.userRole
        })
        
        // 关闭对话框，结果将通过WebSocket事件处理
        importDialog.value = false
      } catch (error) {
        console.error('处理Excel文件错误:', error)
        window.showNotification?.('处理Excel文件错误: ' + error.message, 'error')
      } finally {
        importing.value = false
        importFile.value = null // 清空文件选择，以便再次选择同一文件
      }
    }
    
    reader.onerror = () => {
      window.showNotification?.('读取文件错误', 'error')
      importing.value = false
      importFile.value = null
    }
    
    reader.readAsArrayBuffer(importFile.value)
  } catch (error) {
    console.error('导入学生错误:', error)
    window.showNotification?.('导入学生错误: ' + error.message, 'error')
    importing.value = false
    importFile.value = null
  }
}

// WebSocket事件监听器引用，用于重连后重新设置
let studentsImportResultListener = null
let studentStatusUpdatedListener = null

// 设置WebSocket事件监听器
const setupSocketListeners = () => {
  // 清理旧的监听器
  cleanupSocketListeners()
  
  // 确保socket存在
  if (!socketStore.socket) {
    console.warn('Socket未初始化，无法设置监听器')
    return
  }
  
  // 监听学生导入结果
  studentsImportResultListener = (data) => {
    importing.value = false
    importFile.value = null
    
    if (data.success) {
      window.showNotification?.(`成功导入${data.imported}个学生`, 'success')
      
      // 显示错误信息（如果有）
      if (data.errors && data.errors.length > 0) {
        console.error('导入错误:', data.errors)
        window.showNotification?.(`${data.errors.length}条记录导入失败`, 'warning')
      }
      
      // 刷新学生列表
      loadStudents()
    } else {
      window.showNotification?.(data.message || '导入学生失败', 'error')
    }
  }
  
  // 监听学生状态更新
  studentStatusUpdatedListener = () => {
    loadStudents() // 刷新学生列表
  }
  
  // 设置监听器
  socketStore.socket.on('students-import-result', studentsImportResultListener)
  socketStore.socket.on('student-status-updated', studentStatusUpdatedListener)
  
  // 重要：设置学生数据监听器，确保WebSocket重连后能正常接收学生列表数据
  studentsStore.initSocketListeners()
}

// 清理WebSocket事件监听器
const cleanupSocketListeners = () => {
  if (socketStore.socket) {
    if (studentsImportResultListener) {
      socketStore.socket.off('students-import-result', studentsImportResultListener)
    }
    if (studentStatusUpdatedListener) {
      socketStore.socket.off('student-status-updated', studentStatusUpdatedListener)
    }
  }
}

// 监听WebSocket连接状态变化，重连后重新设置监听器
const setupConnectionWatcher = () => {
  if (socketStore.socket) {
    socketStore.socket.on('connect', () => {
      console.log('WebSocket重连成功，重新设置事件监听器')
      setupSocketListeners()
    })
  }
}

/**
 * 等待WebSocket连接建立
 * @returns {Promise<void>}
 */
const waitForConnection = () => {
  return new Promise((resolve) => {
    if (socketStore.isConnected) {
      resolve()
    } else {
      const checkConnection = () => {
        if (socketStore.isConnected) {
          resolve()
        } else {
          setTimeout(checkConnection, 100)
        }
      }
      checkConnection()
    }
  })
}

/**
 * 初始化数据加载
 * @param {string|null} classId - 班级ID
 */
const initializeData = async (classId = null) => {
  try {
    // 等待WebSocket连接建立
    await waitForConnection()
    
    // 并行加载基础数据
    await Promise.all([
      loadClasses(),
      loadDrivers()
    ])
    
    // 设置班级筛选条件
    if (classId) {
      selectedClass.value = parseInt(classId)
    } else {
      selectedClass.value = ''
    }
    
    // 等待DOM更新
    await nextTick()
    
    // 加载学生数据
    await loadStudents()
  } catch (error) {
    console.error('数据初始化失败:', error)
    window.showNotification?.('数据加载失败，请刷新页面重试', 'error')
  }
}

// 生命周期钩子
onMounted(async () => {
  // 设置WebSocket事件监听器
  setupSocketListeners()
  
  // 设置连接状态监听器，确保重连后重新设置事件监听器
  setupConnectionWatcher()
  
  // 初始化数据，如果URL中有classId参数则传入
  const classId = route.query.classId
  await initializeData(classId)
})

// 组件卸载时清理监听器
onUnmounted(() => {
  cleanupSocketListeners()
  
  // 清理连接状态监听器
  if (socketStore.socket) {
    socketStore.socket.off('connect')
  }
})

// 监听路由变化，支持动态切换班级
watch(() => route.query, async (newQuery, oldQuery) => {
  // 检查是否是新的路由跳转（避免重复加载）
  if (newQuery.classId !== oldQuery?.classId) {
    if (newQuery.classId) {
      selectedClass.value = parseInt(newQuery.classId)
    } else {
      selectedClass.value = ''
    }
    // 等待DOM更新
    await nextTick()
    // 等待连接后重新加载学生数据
    await waitForConnection()
    await loadStudents()
  }
}, { immediate: false })
</script>

<style scoped>
.v-data-table {
  border-radius: 8px;
}

#qr-code-container img {
  max-width: 200px;
  height: auto;
}

.v-btn {
  margin-left: 20px;
}
</style>
